<?php

App::import('Model', 'User');
App:: import('Model', 'FutureTweet');
App:: import('Model', 'Accounts_has_user');
App:: import('Model', 'Post');
App:: import('Controller', 'FutureTweets');

class EventsController extends AppController {
    /**
     * Description of Index
     * Sets the home page for events selects all events belonging to a certain account
     * @author Mina Samy
     */

    public function index() {
        $this->loadModel('User');
        $this->loadModel('FutureTweet');
        $userID = $this->Auth->User('userID');
        $accID = $this->Auth->User('accID');
        if ($accID == null) {
            $this->set('events', array());
            $this->set('names', array());
            $this->set('eventsstatus', array());
            $this->Session->setFlash('You are not logged in with an account');
            return;
        }
        if ($this->User->getPermissionLevel($accID, $userID) >= 1 OR $this->User->isAdmin($userID) == true) {
            $events1 = $this->Event->getEvents($accID);
            $status = array();
            for ($j = 0; $j < sizeof($events1); $j++) {
                $status[$j] = $this->FutureTweet->isApproved($events1[$j]['Event']['id']);
            }
            $this->set('events', $events1);
            $this->set('eventsstatus', $status);
            $ids = array();
            for ($i = 0; $i < sizeof($events1); $i++) {
                $ids[$i] = $events1[$i]['Event']['creatorID'];
            }
            $this->set('names', $this->User->getNames($ids));
            if ($this->Event->getEvents($accID) == array()) {
                $this->Session->setFlash('There are no events in this account');
            }
        } else {
            $this->Session->setFlash('You are not authorized to to view these events');
        }
    }

    /**
     * Description of Function View
     * @id
     * Views the contents of a certain event its name and describtion and selects all the tweets that were posted to twitter or not
     * posted yet and it is allowed for all users assigned to a certain account as it doesnt allow for any edit
     * @return void
     * @author Mina Samy
     */

    public function view($id = null) {
        $this->loadModel('User');
        $userID = $this->Auth->User('userID');
        $accID = $this->Auth->User('accID');
        if ($this->User->getPermissionLevel($accID, $userID) >= 1 OR $this->User->isAdmin($userID) == true) {
            $this->Event->id = $id;
            $this->set('event', $this->Event->read(NULL, $id));
            $this->loadModel('Post');
            $postedtweets = $this->Post->getEventTweets($id);


            $this->loadModel('FutureTweet');
            $futuretweets = $this->FutureTweet->getEventFutureTweets($id);
            $alltweets = array();
            $i = 0;
            while ($i < sizeof($postedtweets)) {
                $alltweets[$i] = array(true, $postedtweets[$i]['Post']['text'], $postedtweets[$i]['Post']['time']);
                $i++;
            }

            $j = 0;
            while ($j < sizeof($futuretweets)) {
                $alltweets[$i] = array(false, $futuretweets[$j]['FutureTweet']['tweetText'], $futuretweets[$j]['FutureTweet']['release_date']);
                $j++;
                $i++;
            }

            for ($k = 0; $k < sizeof($alltweets); $k++) {
                for ($l = 0; $l < sizeof($alltweets); $l++) {
                    if ($alltweets[$l][2] > $alltweets[$k][2]) {
                        $temp = $alltweets[$l];
                        $alltweets[$l] = $alltweets[$k];
                        $alltweets[$k] = $temp;
                    }
                }
            }
            $this->set('eventtweets', $alltweets);
        } else {
            $this->Session->setFlash('You are not authorized to view this event');
            $this->redirect(array('action' => 'index'));
        }
    }

    /**
     * Description of Function add
     * Adds an event to the Account of ID = @accid and is inserted by user with id = @userID it takes the name and describtion of the Event
     * using text boxes
     * @return void
     * @author Mina Samy
     */

    public function add() {
        $this->loadModel('User');
        $userID = $this->Auth->User('userID');
        $accID = $this->Auth->User('accID');
        if ($accID == null) {
            $this->Session->setFlash('You are not logged in with an account');
            $this->redirect(array('action' => 'index'));
        }
        if ($this->User->getPermissionLevel($accID, $userID) >= 1 OR $this->User->isAdmin($userID) == true) {
            if ($this->request->is('post')) {
                $this->request->data['Event']['creatorID'] = $userID;
                $this->request->data['Event']['accountID'] = $accID;
                $this->request->data['Event']['deleted'] = false;
                if ($this->Event->save($this->request->data)) {
                    $this->Session->setFlash('Your Event has been saved.');
                    $this->redirect(array('action' => 'index'));
                } else {
                    $this->Session->setFlash('Unable to add your Event.');
                }
            }
        } else {
            $this->Session->setFlash('You are not authorized to add events');
            $this->redirect(array('action' => 'index'));
        }
    }





    /**
     * Description of Function Edit
     * @param int $id
     * allows for editing the event with id = @id the editing can be either by inserting new tweets submitting the event saving and exiting or 
     * changing the event information title and describtion
     * @return void
     * @author Mina Samy
     */

    public function edit($id = null) {
        $this->loadModel('User');
        $this->loadModel('FutureTweet');
        $userID = $this->Auth->User('userID');
        $accID = $this->Auth->User('accID');
        $permission = $this->User->getPermissionLevel($accID, $userID);
        $creator = $this->Event->isCreator($userID, $id);
        $admin = $this->User->isAdmin($userID);
        if ($permission >= 3 OR $creator OR $admin) {
            if ($this->FutureTweet->isApproved($id) AND !$admin AND $permission == 1) {
                $this->FutureTweet->ApproveEvent($id, 0);
                $this->Session->setFlash('Since this event is editted after approval it will need to be reapproved.');
            }

            $this->loadModel('FutureTweet');
            $tweets = $this->FutureTweet->getEventFutureTweets($id);
            $repeatedtimes = array();
            for ($j = 0; $j < sizeof($tweets); $j++) {
                $repeatedtimes[$j] = $this->FutureTweet->getrepetitions($id, $tweets[$j]['FutureTweet']['tweetText']);
                if ($repeatedtimes[$j] > 0) {
                    for ($i = $j + 1; $i < sizeof($tweets); $i++) {

                        if (strcmp($tweets[$j]['FutureTweet']['tweetText'], $tweets[$i]['FutureTweet']['tweetText']) == 0) {
                            unset($tweets[$i]);
                            $tweets = array_values($tweets);
                            $i--;
                        }
                    }
                }
            }
            $this->set('repetitions', $repeatedtimes);
            $this->set('eventtweets', $tweets);
            $ids = array();
            for ($i = 0; $i < sizeof($tweets); $i++) {
                $ids[$i] = $tweets[$i]['FutureTweet']['userID'];
            }

            $this->set('names1', $this->User->getNames($ids));
            $this->Event->id = $id;
            $this->set('id', $id);
            if ($this->request->is('get')) {
                $this->request->data = $this->Event->read();
            } else {
                if ($this->Event->save($this->request->data)) {
                    $this->Session->setFlash('Your Event has been updated.');
                    $this->redirect(array('action' => 'index'));
                } else {
                    $this->Session->setFlash('Unable to update your Event.');
                }
            }
        } else {
            $this->Session->setFlash('You are not authorized to edit this event');
            $this->redirect(array('action' => 'index'));
        }
    }







/**
 * Description of edittweet
 * @param  int $id
 * @param  int $eventID
 * @param  String $text
 *Y: the function lets the user edit a tweet in an event
 * @return void
 * @author "Mina Samy"
 */
    
    public function editTweet($id = null , $eventID = null , $text = null) {
        $this->loadModel('FutureTweet');
        $this->loadModel('User');
        if(empty($this->data)) {
            $this->data = $this->FutureTweet->read(Null,$id);
        }
         else {
            $accountID=$this->Auth->User('accID');
            $userID=$this->Auth->User('userID');
            $permission =$this->User->getPermissionLevel($accountID,$userID);

            $data = $this->request->data['FutureTweet']['release_date'];
            $tweetText = $this->request->data['FutureTweet']['tweetText'];
            $isAdmin = $this->User->isAdmin($userID);
            $creator = $this->Event->isCreator($userID, $eventID);
            if($permission == 3 OR $isAdmin OR $creator) {

                $current_time = date('Y-m-d H:i:s');
                list($CYear, $CMonth, $CDay, $CClock) = split('[ .-]', $current_time);
                list($CHour, $CMinute, $CSecond) = split('[:.-]', $CClock);
                list($Year, $Month, $Day, $Clock) = split('[ .-]', $data);
                list($Hour, $Minute, $Second) = split('[:.-]', $Clock);

                if((empty($Year))OR(empty($Month))OR(empty($Day))OR(empty($Hour))OR(empty($Minute))OR(empty($Second)))
                {
                    $this->Session->setFlash('Wrong time input');
                    return;
                }

                if((!(is_numeric($Year)))OR(!(is_numeric($Month)))OR(!(is_numeric($Day)))OR(!(is_numeric($Hour)))OR(!(is_numeric($Minute)))OR(!(is_numeric($Second))))
                {
                    $this->Session->setFlash('Please enter date and time in form of numbers');
                    return;   
                }

                if((!((0 < $Month) && ($Month < 13))) OR (!((0 < $Day) && ($Day < 32))) OR (!((-1 < $Hour) && ($Hour < 24))) OR (!((-1 < $Minute) && ($Minute < 60))) OR (!((-1 < $Second) && ($Second < 60))))
                {
                    $this->Session->setFlash('Wrong Input, Please enter input within the correct interval');
                    return;   
                }

                if(strtotime($data) < strtotime($current_time))
                {
                    $this->Session->setFlash('The Release time for this tweet has already passed');
                    return;
                }

                if($permission > 1 OR $isAdmin)
                {
                    $approved = true;
                }
                else 
                {
                    $approved = false;
                }
                   $tweet = array('userID' => $userID, 'tweetText' => $tweetText,
                'eventID' => $eventID, 'approved' => $approved,
                'release_date' => $data,'accID' => $accountID); 
                    $old = $this->FutureTweet->find('first',array('FutureTweet.id'=>$id));
                    $this->FutureTweet->delete($id);
                    $message = $this->FutureTweet->insertTweet($tweet);
                    switch ($message) {
                        case 0:
                             echo 'Tweet has been eddited Successfully';
                            break;
                        case -2:
                            echo 'You have violated the Minimum time duration please change the date';
                            $tweet = array('userID' => $old['userID'], 'tweetText' => $$old['tweetText'],
                                  'eventID' => $old['eventID'], 'approved' => $old['approved'],
                                  'release_date' => $old['release_date'],'accID' => $old['accID']); 
                            $this->FutureTweet->insertTweet($tweet);
                            break;
                        case -3:
                            echo 'Internal Error';
                            $tweet = array('userID' => $old['userID'], 'tweetText' => $$old['tweetText'],
                                  'eventID' => $old['eventID'], 'approved' => $old['approved'],
                                  'release_date' => $old['release_date'],'accID' => $old['accID']); 
                            $this->FutureTweet->insertTweet($tweet);
                            break;
                    }

                    if($message == 0)
                    {
                        
                        if($text == null)
                        {
                            $this->redirect(array('action'=>'edit', $eventID));
                        }
                        else
                        {
                            $this->redirect(array('action'=>'editTweetrepeated', $text , $eventID ));
                        }
                    }

                }
                else{
                    
                    $this->Session->setFlash('You are not allowed to edit this tweet');
                    $this->redirect(array('action'=>'edit', $eventID));
                }
        }
    }




    /**
 * Description of edittweet
 * @param  int $id
 * @param  int $eventID
 * Y: the function will let the user edit a repeated tweet in an event
 * @return void
 * @author "Mina Samy"
 */
    
    public function editTweetrepeated($text = null , $eventID = null) {
        $this->loadModel('FutureTweet');
        $this->loadModel('User');
        $accountID=$this->Auth->User('accID');
        $userID=$this->Auth->User('userID');
        $permission =$this->User->getPermissionLevel($accountID,$userID);
        $isAdmin = $this->User->isAdmin($userID);
        $creator = $this->Event->isCreator($userID, $eventID);
        if($permission == 3 OR $isAdmin OR $creator) {
                $repeatedtweets = $this->FutureTweet->getEventFutureRepeatedTweet($eventID , $text);
                $this->set('tweettext',$text);
                for ($k = 0; $k < sizeof($repeatedtweets); $k++) {
                for ($l = 0; $l < sizeof($repeatedtweets); $l++) {
                    if ($repeatedtweets[$k]['FutureTweet']['release_date'] < $repeatedtweets[$l]['FutureTweet']['release_date']) {
                        $temp = $repeatedtweets[$l];
                        $repeatedtweets[$l] = $repeatedtweets[$k];
                        $repeatedtweets[$k] = $temp;
                    }
                }
            }
                $this->set('tweets', $repeatedtweets);
                }
        else{            
                $this->Session->setFlash('You are not allowed to edit this tweet');
                $this->redirect(array('action'=>'edit', $eventID));
            }
        }











    /**
     * Description of Function save
     * @param int $id
     * sets the saved field in all the tweets of this event to true so that the system knows that the event is not ready yet to be launched and 
     * it wouldnt be shown to the moderator for approval in the future timeline
     * @return void
     * @author Mina Samy
     */
    public function save($id = null) {
        $this->loadModel('User');
        $userID = $this->Auth->User('userID');
        $accID = $this->Auth->User('accID');
        $permission = $this->User->getPermissionLevel($accID, $userID);
        if ($permission >= 3 OR $this->Event->isCreator($userID, $id) OR $this->User->isAdmin($userID) == true) {
            $this->loadModel('FutureTweet');
            $this->FutureTweet->EventSaving($id, 1, $permission);
            $this->Event->setStatus($id, 0);
            $this->redirect(array('action' => 'index'));
            $this->Session->setFlash('Your Event tweets are now saved and wont be launched until you click submit event');
        } else {
            $this->Session->setFlash('You are not authorized to save this event');
            $this->redirect(array('action' => 'index'));
        }
    }

    /**
     * Deletes the event with ID = $id and all its tweets from the database 
     * @param  int $id.
     * author : "Mina Samy"
     * @return void
     */
    public function deleteevent($id = null) {
        $this->loadModel('User');
        $userID = $this->Auth->User('userID');
        $accID = $this->Auth->User('accID');
        $permission = $this->User->getPermissionLevel($accID, $userID);
        if ($permission >= 3 OR $this->Event->isCreator($userID, $id) OR $this->User->isAdmin($userID) == true) {
            $this->loadModel('FutureTweet');
            $this->FutureTweet->deleteeventtweets($id);
            $this->Event->id = $id;
            $theevent = $this->Event->read();
            $theevent['Event']['deleted'] = true;
            $this->Event->save($theevent);
            $this->autoRender = false;
            $this->Session->setFlash('The Event has been deleted successfuly.');
            $this->redirect(array('action' => 'index'));
        } else {
            $this->Session->setFlash('You are not authorized to delete this event');
            $this->redirect(array('action' => 'index'));
        }
    }

    /**
     * Deletes all the tweets of a certain event with ID = $id where it has tweettext = $text  
     * @param  int $id.
     * @param  String $text
     * author : "Mina Samy"
     * @return void
     */
    public function deleteeventtweet($id = null , $eventID = null  , $text = null) {
        $this->loadModel('User');
        $userID = $this->Auth->User('userID');
        $accID = $this->Auth->User('accID');
        $permission = $this->User->getPermissionLevel($accID, $userID);
        if ($permission >= 3 OR $this->Event->isCreator($userID, $eventID) OR $this->User->isAdmin($userID) == true) {
            $this->loadModel('FutureTweet');
            $this->FutureTweet->delete($id);
            $this->autoRender = false;
            if($text == null)
            {
                $this->redirect(array('action' => 'edit', $eventID));
            }
            else
            {
                $this->redirect(array('action' => 'editTweetrepeated', $text , $eventID));
            }
        } else {
            $this->Session->setFlash('You are not authorized to delete this tweet');
        }
    }

        /**
     * Deletes all the tweets of a certain event with ID = $id where it has tweettext = $text  
     * @param  int $id.
     * @param  String $text
     * author : "Mina Samy"
     * @return void
     */
    public function deleteallrepeated($text = null , $eventID = null , $tweetinsertiontime = null) {
        $this->loadModel('User');
        $userID = $this->Auth->User('userID');
        $accID = $this->Auth->User('accID');
        $permission = $this->User->getPermissionLevel($accID, $userID);
        if ($permission >= 3 OR $this->Event->isCreator($userID, $eventID) OR $this->User->isAdmin($userID) == true) {
            $this->loadModel('FutureTweet');
            $this->FutureTweet->deleterepeated($text , $eventID , $tweetinsertiontime);
            $this->autoRender = false;
            $this->redirect(array('action' => 'edit', $eventID));
    
        } else {
            $this->Session->setFlash('You are not authorized to delete this tweet');
        }
    }








    /**
     * Description of Function submit
     * @param int $id
     * sets the saved field in all the tweets of this event to FALSE so that the system knows that the event is ready to be launched and 
     * it wouldnt be shown to the moderator for approval if it needs approval
     * @return void
     * @author Mina Samy
     */

    public function submit($id = null) {

        $this->loadModel('User');
        $userID = $this->Auth->User('userID');
        $accID = $this->Auth->User('accID');
        $permission = $this->User->getPermissionLevel($accID, $userID);
        if ($permission >= 3 OR $this->Event->isCreator($userID, $id) OR $this->User->isAdmin($userID) == true) {
            $this->loadModel('FutureTweet');
            if ($permission >= 2 OR $this->User->isAdmin($userID) == true) {
                $this->FutureTweet->ApproveEvent($id, 1);
            }
            $this->FutureTweet->EventSaving($id, 0);
            $this->Event->setStatus($id, 1);
            $this->redirect(array('action' => 'index'));
            $this->Session->setFlash('Your Event has been submitted to stop its launch you have to edit it and click save and exit');
        } else {
            $this->redirect(array('action' => 'index'));
            $this->Session->setFlash('You are not authorized to submit this event');
        }
    }

    /**
     * Description of Function approve
     * @param int $id
     * @param String $status
     * sets the approved field in all the tweets of this event to true 
     * @return void
     * @author Mina Samy
     */

    public function approve($id = null, $status = null) {
        $this->loadModel('User');
        $this->loadModel('FutureTweet');
        $userID = $this->Auth->User('userID');
        $accID = $this->Auth->User('accID');
        if ($this->User->getPermissionLevel($accID, $userID) >= 3 OR $this->User->isAdmin($userID) == true) {
            if ($this->FutureTweet->isApproved($id)) {
                $this->Session->setFlash('This Event is Already approved.');
                $this->redirect(array('action' => 'index'));
            }
            if ($status == 'incomplete') {
                $this->Session->setFlash('This Event is not complete yet and cant be approved.');
                $this->redirect(array('action' => 'index'));
            } else {

                $this->FutureTweet->ApproveEvent($id, 1);
                $this->Session->setFlash('The Event has been approved successfuly.');
                $this->redirect(array('action' => 'index'));
            }
        } else {
            $this->Session->setFlash('You are not authorized to Approve this event');
            $this->redirect(array('action' => 'index'));
        }
    }

    /* Description of AddTweet function
     * 
     * @eventID
     * @userID
     * @accID
     * 
     * The function AddTweet takes the URL parameters which are the userID, eventID and accID and then gets
     * from the user everything related to the added tweet which are (tweetText, startDate, 
     * numberOfRepetitions) and produces the current using time of the function (sub_time) and generates
     * the permission of the current user for the account it's using, and from it the function knows if
     * the tweet is initially approved or not. At last, it checks if the tweet was NOT to be repeated,
     * it calls the method insertTweet from the FutureTweetsController, otherwise it calls the method that
     * repeats the tweet "repeatTweet" from the same controller giving any of them an array with all data
     * deduced (userID, tweetText, eventID, approved, release_date, sub_time, accID) for any of those
     * functions to carryon the procedures. Also handling in between if the user wants to use the force delete
     * option or not, and if yes the function should make sure that the info given including the interval and the
     * maximum number of repetitions per day are appropiate and could be possibly applied or not.
     * 
     * @return void
     * 
     * @author: Ahmad AboulAzm
     * 
     */

    public function AddTweet($id = null) {
        $this->set('id', $id);
        $this->loadModel('User');
        $userID = $this->Auth->User('userID');
        $accID = $this->Auth->User('accID');

        if (!empty($this->request->data)) {

            $tweetText = $this->request->data['Event']['Tweet'];

            $Repeated = $this->request->data['Event']['Repeated'];
            $ForceDeleteMode = $this->request->data['Event']['ForceDeleteMode'];

            $eventID = $this->request->data['Event']['eventID'];

            $date1 = $this->request->data['Event']['Start Date'];
            $clock1 = $this->request->data['Event']['Clock1 (hh:mm)'];

            if ((empty($tweetText)) OR (empty($date1)) OR (empty($clock1))) {
                $this->Session->setFlash("Required fields empty !");
                return;
            }

            list($StartDateDay, $StartDateMonth, $StartDateYear) = split('[/.-]', $date1);
            list($StartDateHour, $StartDateMinute) = split('[:.-]', $clock1);

            if (empty($StartDateHour) OR empty($StartDateMinute)
                    OR !is_numeric($StartDateHour) OR !is_numeric($StartDateMinute)
                    OR $StartDateHour > 23 OR $StartDateHour < 0
                    OR $StartDateMinute < 0 OR $StartDateMinute > 59) {
                $this->Session->setFlash("Invalid clock input !");
                return;
            }


            if (empty($StartDateDay) OR empty($StartDateMonth) OR empty($StartDateYear)
                    OR !is_numeric($StartDateDay) OR !is_numeric($StartDateMonth)
                    OR !is_numeric($StartDateYear) OR $StartDateDay > 31 OR $StartDateDay < 0
                    OR $StartDateMonth < 0 OR $StartDateMonth > 12) {
                $this->Session->setFlash("Invalid date input !");
                return;
            }


            $startDateSecond = '00';
            $release_date = $StartDateYear . '-' . $StartDateMonth . '-' . $StartDateDay . ' ' . $StartDateHour . ':' . $StartDateMinute . ':' . $startDateSecond;
            $sub_time = date('Y-m-d H:i:s');

            if (strtotime($release_date) < time()) {
                $this->Session->setFlash("input date cant be before today's date !");
                return;
            }

            $permission = $this->User->getPermissionLevel($accID, $userID);
            $isAdmin = $this->User->isAdmin($userID);
            if ($permission > 1 OR $isAdmin) {
                $approved = 1;
            } else {
                $approved = 0;
            }


            $f = array('userID' => $userID, 'tweetText' => $tweetText,
                'eventID' => $eventID, 'approved' => $approved,
                'release_date' => $release_date, 'sub_time' => $sub_time,
                'accID' => $accID);
            if ($Repeated == '0') {
                ClassRegistry::init('FutureTweet')->insertTweet($f);
                $this->redirect(array('action' => 'edit', $eventID));
            } else {
                $date2 = $this->request->data['Event']['End Date'];
                list($EndDateDay, $EndDateMonth, $EndDateYear) = split('[/.-]', $date2);
                $endDate = $EndDateYear . '-' . $EndDateMonth . '-' . $EndDateDay;
                if (strtotime($endDate) < strtotime($release_date)) {
                $this->Session->setFlash("end date cant be before Repetition start date !");
                return;
            }
                $NumberOfRepetitions = $this->request->data['Event']['NumberOfRepetitions'];
                $MaxNoOfRepetitionsPerDay = $this->request->data['Event']['MaxNoOfRepetitionsPerDay'];

                if ($ForceDeleteMode == '1') {
                    if (empty($EndDateDay) OR empty($EndDateMonth) OR empty($EndDateYear)
                            OR !is_numeric($EndDateDay) OR !is_numeric($EndDateMonth)
                            OR !is_numeric($EndDateYear) OR $EndDateDay > 31 OR $EndDateDay < 0
                            OR $EndDateMonth < 0 OR $EndDateMonth > 12) {
                        $this->Session->setFlash("Invalid date input !");
                        return;
                    }

                    if (($EndDateYear == $StartDateYear) && ($EndDateMonth == $StartDateMonth)) {
                        if (!($NumberOfRepetitions <= (($EndDateDay - $StartDateDay) * $MaxNoOfRepetitionsPerDay))) {
                            $this->Session->setFlash("Invalid combination of Number of days & max number of repetitions per day 1");
                            return;
                        }
                    } else {
                        if ($StartDateYear == $EndDateYear) {
                            if (!($NumberOfRepetitions <= (((($EndDateMonth - $StartDateMonth) * 30) + (30 - $StartDateDay) + ($EndDateDay)) * $MaxNoOfRepetitionsPerDay))) {
                                $this->Session->setFlash("Invalid combination of Number of days & max number of repetitions per day 2");
                                return;
                            }
                        } else {
                            if (!($NumberOfRepetitions <= ((($EndDateYear - $StartDateYear) * 365) + (((12 - $StartDateMonth) + ($EndDateMonth)) * 30)
                                    + ((30 - $StartDateDayDateDay) + $EndDateDay)))) {
                                $this->Session->setFlash("Invalid combination of Number of days & max number of repetitions per day 3");
                                return;
                            }
                        }
                    }


                    if (!is_numeric($MaxNoOfRepetitionsPerDay) OR ($MaxNoOfRepetitionsPerDay < 0)) {
                        $this->Session->setFlash("Invalid value for maximum number of repetitions per day !");
                        return;
                    }

                    if (empty($MaxNoOfRepetitionsPerDay)) {
                        $this->Session->setFlash("Required field number of max number repetitions per day is empty !");
                        return;
                    }
                } else {
                    if (empty($date2)) {
                        $this->Session->setFlash("End Date field empty !");
                        return;
                    }
                }

                if (!is_numeric($NumberOfRepetitions) OR ($NumberOfRepetitions < 0)) {
                    $this->Session->setFlash("Invalid value for number of repetitions !");
                    return;
                }

                if (empty($NumberOfRepetitions)) {
                    $this->Session->setFlash("Required field number of repetitions is empty !");
                    return;
                }

                $endDate = $EndDateYear . '-' . $EndDateMonth . '-' . $EndDateDay;
                $this->repeatTweet($f, $NumberOfRepetitions, $endDate);
                $this->redirect(array('action' => 'edit', $eventID));
            }
        }
    }

    /**
     * This function repeats the given tweet $no times in the given $noofdays 
     * @param array $tweet The new tweet to be added
     * @param int $no The number of repetitions of the tweet
     * @param Date $enddate the end date of repetition process
     * @author Mina Samy
     * @return void
     */
    public function repeatTweet($tweet = null, $no = null, $enddate = null) {

        $interval = strtotime($enddate) - strtotime($tweet['release_date']);
        $minutestobedivided = $interval / 60;
        $minutesadded = ($minutestobedivided - ($minutestobedivided % $no)) / $no;
        $datetime = $tweet['release_date'];
        $dateandtime = explode(" ", $datetime);
        list($StartDateYear, $StartDateMonth, $StartDateDay ) = split('[/.-]', $dateandtime[0]);
        list($StartDateHour, $StartDateMinute, $StartDateSecond) = split('[:.-]', $dateandtime[1]);
        $this->loadModel('FutureTweet');
        $this->FutureTweet->insertTweet($tweet);

        for ($i = 1; $i < $no; $i++) {
            $added = $minutesadded;
            $StartDateMinute = $StartDateMinute + $added;
            while ($StartDateMinute > 59) {
                $StartDateMinute = $StartDateMinute - 60;
                $StartDateHour = $StartDateHour + 1;
            }

            while ($StartDateHour > 23) {
                $StartDateHour = $StartDateHour - 24;
                $StartDateDay = $StartDateDay + 1;
            }

            while ($StartDateDay > 31) {
                if ($StartDateMonth == 2 and $StartDateDay > 28) {
                    $StartDateDay = $StartDateDay - 28;
                    $StartDateMonth = 3;
                } else {
                    if (($StartDateMonth == 1 OR $StartDateMonth == 3 OR $StartDateMonth == 5 OR $StartDateMonth == 7
                            OR $StartDateMonth == 8 OR $StartDateMonth == 10 OR $StartDateMonth == 12) and $StartDateDay > 31) {
                        $StartDateDay = $StartDateDay - 31;
                        $StartDateMonth++;
                    } else {
                        if (($StartDateMonth == 4 OR $StartDateMonth == 6 OR $StartDateMonth == 9
                                OR $StartDateMonth == 11) and $StartDateDay > 30) {
                            $StartDateDay = $StartDateDay - 30;
                            $StartDateMonth++;
                        }
                    }
                }
            }
            while ($StartDateMonth > 12) {
                $StartDateMonth = $StartDateMonth - 12;
                $StartDateYear = $StartDateYear + 1;
            }

            $release_date = $StartDateYear . '-' . $StartDateMonth . '-' . $StartDateDay . ' ' . $StartDateHour . ':' . $StartDateMinute . ':' . $StartDateSecond;
            $tweet['release_date'] = $release_date;
            $this->FutureTweet->insertTweet($tweet);
        }

        $tweets = $this->FutureTweet->getEventFutureRepeatedTweet($tweet['eventID'], $tweet['tweetText']);
        for ($j = 0; $j < sizeof($tweets); $j++) {
            $tweetstocallfunction[$j] = $tweets[$j]['FutureTweet']['id'];
        }
        $this->FutureTweet->addRandomVariance($tweetstocallfunction);
    }




    /*
     * Description of tweetRepeatedNumber
     * @eventid
     * @text
     * get the number of repeatetion of the tweet in the FutureTweet
     *
     *@return $count
     * @author Youssef Madkour
     */

    public function tweetRepeatedNumber($eventid, $text) {
        $this->loadModel("FutureTweet");
        $condition = array("FutureTweet.tweetText" => $text, "FutureTweet.eventId " => $eventid);
        $count = $this->FutureTweet->find('count', array('conditions' => $condition));
        $this->set('count', $count);

        return $count;
    }

    /*
     * Description of tweetRepeatedNumber
     * @eventid
     * @text
     * get the time of the first tweet in the event that should be posted
     *
     *@return $date;
     * @author Youssef Madkour
     */

    public function getFirstEventTweetDate($eventid, $text) {
        $this->loadModel("FutureTweet");
        $condition = array("FutureTweet.tweetText" => $text, "FutureTweet.eventId " => $eventid);
        $date = $this->FutureTweet->field('release_date', $condition, "");
        $this->set('firstdate', $date->format('Y-m-d'));
        return $date;
    }

    /*
     * Description of tweetRepeatedNumber
     * @eventid
     * @text
     * get the time of the last tweet in the event that should be posted
     *
     *@return $date->format('Y-m-d');
     * @author Youssef Madkour
     */

    public function getLastEventTweetDate($date) {


        $this->loadModel("FutureTweet");
        $date = new DateTime(date('Y-m-d H:i:s'));

        $date->modify('+ ' . $date . ' day');
        $this->set('lastdate', $date->format('Y-m-d'));
        return $date->format('Y-m-d');
    }

    /* Description of AddTweetLayout function
     * 
     * @param eventID
     * @param userID
     * @param accID
     * 
     * This function is implemented the same was as the previous one addTweet the only difference it direct to  Futuretweet page 
     * 
     * @return void
     * 
     * @author: Youssef Madkour
     * 
     */

    public function AddTweetLayout($id = null) {
        $this->set('id', $id);
        $this->loadModel('User');
        $userID = $this->Auth->User('userID');
        $accID = $this->Auth->User('accID');

        if (!empty($this->request->data)) {

            $tweetText = $this->request->data['Event']['Tweet'];

            $Repeated = $this->request->data['Event']['Repeated'];
            $ForceDeleteMode = $this->request->data['Event']['ForceDeleteMode'];

            $eventID = NULL;

            $date1 = $this->request->data['Event']['Start Date'];
            $clock1 = $this->request->data['Event']['Clock1 (hh:mm)'];

            if ((empty($tweetText)) OR (empty($date1)) OR (empty($clock1))) {
                $this->Session->setFlash("Required fields empty !");
                 $this->redirect(array('controller' => 'FutureTweets', 'action' => 'viewfuturetweets'));
                return;
            }

            list($StartDateDay, $StartDateMonth, $StartDateYear) = split('[/.-]', $date1);
            list($StartDateHour, $StartDateMinute) = split('[:.-]', $clock1);

            if (empty($StartDateHour) OR empty($StartDateMinute)
                    OR !is_numeric($StartDateHour) OR !is_numeric($StartDateMinute)
                    OR $StartDateHour > 23 OR $StartDateHour < 0
                    OR $StartDateMinute < 0 OR $StartDateMinute > 59) {
                $this->Session->setFlash("Invalid clock input !");
             $this->redirect(array('controller' => 'FutureTweets', 'action' => 'viewfuturetweets'));
                return;
            }


            if (empty($StartDateDay) OR empty($StartDateMonth) OR empty($StartDateYear)
                    OR !is_numeric($StartDateDay) OR !is_numeric($StartDateMonth)
                    OR !is_numeric($StartDateYear) OR $StartDateDay > 31 OR $StartDateDay < 0
                    OR $StartDateMonth < 0 OR $StartDateMonth > 12) {
                $this->Session->setFlash("Invalid date input !");
             $this->redirect(array('controller' => 'FutureTweets', 'action' => 'viewfuturetweets'));
                return;
            }


            $startDateSecond = '00';
            $release_date = $StartDateYear . '-' . $StartDateMonth . '-' . $StartDateDay . ' ' . $StartDateHour . ':' . $StartDateMinute . ':' . $startDateSecond;
            $sub_time = date('Y-m-d H:i:s');

            if (strtotime($release_date) < time()) {
                $this->Session->setFlash("input date cant be before today's date !");
                 $this->redirect(array('controller' => 'FutureTweets', 'action' => 'viewfuturetweets'));
                return;
            }


            $permission = $this->User->getPermissionLevel($accID, $userID);
            $isAdmin = $this->User->isAdmin($userID);
            if ($permission > 1 OR $isAdmin) {
                $approved = 1;
            } else {
                $approved = 0;
            }


            $f = array('userID' => $userID, 'tweetText' => $tweetText,
                'eventID' => $eventID, 'approved' => $approved,
                'release_date' => $release_date, 'sub_time' => $sub_time,
                'accID' => $accID);
            if ($Repeated == '0') {
                ClassRegistry::init('FutureTweet')->insertTweet($f);
                $this->redirect(array('controller' => 'FutureTweets', 'action' => 'viewfuturetweets'));
            } else {
                $date2 = $this->request->data['Event']['End Date'];
                list($EndDateDay, $EndDateMonth, $EndDateYear) = split('[/.-]', $date2);
                $endDate = $EndDateYear . '-' . $EndDateMonth . '-' . $EndDateDay;
                if (strtotime($endDate) < strtotime($release_date)) {
                $this->Session->setFlash("end date cant be before Repetition start date !");
                $this->redirect(array('controller' => 'FutureTweets', 'action' => 'viewfuturetweets'));
                return;
            }
                $NumberOfRepetitions = $this->request->data['Event']['NumberOfRepetitions'];
                $MaxNoOfRepetitionsPerDay = $this->request->data['Event']['MaxNoOfRepetitionsPerDay'];

                if ($ForceDeleteMode == '1') {
                    if (empty($EndDateDay) OR empty($EndDateMonth) OR empty($EndDateYear)
                            OR !is_numeric($EndDateDay) OR !is_numeric($EndDateMonth)
                            OR !is_numeric($EndDateYear) OR $EndDateDay > 31 OR $EndDateDay < 0
                            OR $EndDateMonth < 0 OR $EndDateMonth > 12) {
                        $this->Session->setFlash("Invalid date input !");
                     $this->redirect(array('controller' => 'FutureTweets', 'action' => 'viewfuturetweets'));
                        return;
                    }

                    if (($EndDateYear == $StartDateYear) && ($EndDateMonth == $StartDateMonth)) {
                        if (!($NumberOfRepetitions < (($EndDateDay - $StartDateDay - 1) * $MaxNoOfRepetitionsPerDay))) {
                            $this->Session->setFlash("Invalid combination of Number of days & max number of repetitions per day 1");
                             $this->redirect(array('controller' => 'FutureTweets', 'action' => 'viewfuturetweets'));
                            return;
                        }
                    } else {
                        if ($StartDateYear == $EndDateYear) {
                            if (!($NumberOfRepetitions < (((($EndDateMonth - $StartDateMonth - 1) * 30) + (30 - $StartDateDay) + ($EndDateDay)) * $MaxNoOfRepetitionsPerDay))) {
                                $this->Session->setFlash("Invalid combination of Number of days & max number of repetitions per day 2");
                                 $this->redirect(array('controller' => 'FutureTweets', 'action' => 'viewfuturetweets'));
                                return;

                            }
                        } else {
                            if (!($NumberOfRepetitions < ((($EndDateYear - $StartDateYear - 1) * 365) + (((12 - $StartDateMonth) + ($EndDateMonth)) * 30)
                                    + ((30 - $StartDateDayDateDay) + $EndDateDay)))) {
                                $this->Session->setFlash("Invalid combination of Number of days & max number of repetitions per day 3");
                             $this->redirect(array('controller' => 'FutureTweets', 'action' => 'viewfuturetweets'));
                                return;
                            }
                        }
                    }


                    if (!is_numeric($MaxNoOfRepetitionsPerDay) OR ($MaxNoOfRepetitionsPerDay < 0)) {
                        $this->Session->setFlash("Invalid value for maximum number of repetitions per day !");
                         $this->redirect(array('controller' => 'FutureTweets', 'action' => 'viewfuturetweets'));
                        return;
                    }

                    if (empty($MaxNoOfRepetitionsPerDay)) {
                        $this->Session->setFlash("Required field number of max number repetitions per day is empty !");
                         $this->redirect(array('controller' => 'FutureTweets', 'action' => 'viewfuturetweets'));
                        return;
                    }
                } else {
                    if (empty($date2)) {
                        $this->Session->setFlash("End Date field empty !");
                         $this->redirect(array('controller' => 'FutureTweets', 'action' => 'viewfuturetweets'));
                        return;
                    }
                }

                if (!is_numeric($NumberOfRepetitions) OR ($NumberOfRepetitions < 0)) {
                    $this->Session->setFlash("Invalid value for number of repetitions !");
                     $this->redirect(array('controller' => 'FutureTweets', 'action' => 'viewfuturetweets'));
                    return;
                }

                if (empty($NumberOfRepetitions)) {
                    $this->Session->setFlash("Required field number of repetitions is empty !");
                     $this->redirect(array('controller' => 'FutureTweets', 'action' => 'viewfuturetweets'));
                    return;
                }


                $this->repeatTweet($f, $NumberOfRepetitions, $date2);
                $this->redirect(array('controller' => 'FutureTweets', 'action' => 'viewfuturetweets'));
            }
        }
    }

}
?>

